
const formatTime = (date) => {
  var date = new Date(date * 1000)
  // const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  // const second = date.getSeconds()

  return [month, day].map(formatNumber).join('月') + '日' + ' ' + [hour, minute].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 当前时间
const newFormatNumber = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumbers).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumbers = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
//计算两个时间之间的时间差
const timedifference = function (faultDate, completeTime) {
  var stime = Date.parse(new Date(faultDate));//获得开始时间的毫秒数
  var etime = Date.parse(new Date(completeTime));//获得结束时间的毫秒数
  var usedTime = etime - stime; //两个时间戳相差的毫秒数
  var days = Math.floor(usedTime / (24 * 3600 * 1000));
  //计算出小时数
  var leave1 = usedTime % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000));//将剩余的毫秒数转化成小时数
  //计算相差分钟数
  var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000));//将剩余的毫秒数转化成分钟
  //计算相差秒数
  var leave3 = leave2 % (60 * 1000);//计算分钟数后剩余的毫秒数
  var seconds = Math.floor(leave3/1000);//将剩余的毫秒数转化成秒数

  var dayStr = days == 0 ? 0 : days;
  var hoursStr = hours == 0 ? 0 : hours;
  var minutesStr = minutes == 0 ? 0 : minutes;
  // var time = dayStr +':'+ hoursStr +':'+ minutesStr +':'+ seconds;
  var time = {day:dayStr,hour:hoursStr,min:minutesStr,sec:seconds}
  return time;
}
//封装form表单的请求
const requestForm=function(method,url, data, callback,loding) {
  if(loding){ }else{
     wx.showLoading({})    //加载动画
  }
  var codes=wx.getStorageSync('addrCode')
  if(codes){
    var addrCode=`${codes.provinceCode},${codes.cityCode},${codes.districtCode},${codes.townCode}`
  }else{
    var addrCode=''
  }
  wx.request({
    method: method,
    url:url,  //服务器地址
    data: data,                                 //请求参数
    header: {
      "Content-Type": "application/x-www-form-urlencoded", // 处理form表单的请求头
      'token': wx.getStorageSync('loginMsg').token,   //请求token
      'firstAccessServerTime': wx.getStorageSync('firstAccessServerTime'),   //当次打开小程序的时间(小程序完全关闭为一次)
      'pricePstCode':wx.getStorageSync('addrCode')!=undefined?(wx.getStorageSync('addrCode').pricePstCode!=undefined?wx.getStorageSync('addrCode').pricePstCode:''):'',
      'cityCode':wx.getStorageSync('addrCode')!=undefined?(wx.getStorageSync('addrCode').cityCode!=undefined?wx.getStorageSync('addrCode').cityCode:''):'',
      'addrCode':addrCode
    },
    dataType: 'json',
    responseType: 'text',
    success: function (res) { 
       wx.hideLoading();  //请求成功后加载动画结束
       return typeof callback == "function" && callback(res)    // 用来判断返回的是否是函数
     },
    fail: function (res) {   //请求失败
       wx.hideLoading();
       wx.showModal({
         title: '网络错误',
         content: '网络出错，请刷新重试',
         showCancel: false
      })
      return typeof callback == "function" && callback(false)
    },
  })
}
const requestJson=function(method,url, data, callback,loding,headers) {
  if(loding){ }else{
    // wx.showLoading({})    //加载动画
  }
  var codes=wx.getStorageSync('addrCode')
  if(codes){
    var addrCode=`${codes.provinceCode},${codes.cityCode},${codes.districtCode},${codes.townCode}`
  }else{
    var addrCode=''
  }
  wx.request({
    method: method,
    url:url,  //服务器地址
    data: data, 
    header:headers|| {
      "Content-Type": "application/json;charset=UTF-8",
      'token': wx.getStorageSync('loginMsg').token,    //请求token
      'firstAccessServerTime': wx.getStorageSync('firstAccessServerTime'),   //当次打开小程序的时间(小程序完全关闭为一次)
      'pricePstCode':wx.getStorageSync('addrCode')!=undefined?(wx.getStorageSync('addrCode').pricePstCode!=undefined?wx.getStorageSync('addrCode').pricePstCode:''):'',
      'cityCode':wx.getStorageSync('addrCode')!=undefined?(wx.getStorageSync('addrCode').cityCode!=undefined?wx.getStorageSync('addrCode').cityCode:''):'',
      'addrCode':addrCode
    },
    dataType: 'json',
    responseType: 'text',
    success: function (res) { 
       wx.hideLoading();  //请求成功后加载动画结束
       return typeof callback == "function" && callback(res)    // 用来判断返回的是否是函数
     },
    fail: function (res) {   //请求失败
      console.log('1111:'+res)
       wx.hideLoading();
       wx.showModal({
         title: '网络错误',
         content: '网络出错，请刷新重试',
         showCancel: false
      })
      return typeof callback == "function" && callback(false)
    },
  })
}
// 将腾讯/高德经纬度 转换为百度地图经纬度
function qqMapTransBMap(lat,lng) {
      let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
      let x = lng;
      let y = lat;
      let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
      let lngs = z * Math.cos(theta) + 0.0065;
      let lats = z * Math.sin(theta) + 0.006;  
      return {
          longitude: lngs,
          latitude: lats 
      }
  } 

// 百度地图经纬度转换为腾讯  / 高德 经纬度
function bMapTransQQMap(lng, lat) {
      let x_pi = 3.14159265358979324 * 3000.0 / 180.0;
      let x = lng - 0.0065;
      let y = lat - 0.006;
      let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
      let lngs = z * Math.cos(theta);
      let lats = z * Math.sin(theta);
      
      return {
          lng: lngs,
          lat: lats        
      }   
  }

  function getImgUrl(url){   //图片地址匹配
    var imgUrl='https://testimg.quanyou.com.cn/' //图片储存服务器地址
    // var imgUrl='https://gcenterimg.quanyou.com.cn/' //正式版 储存服务器地址 发版路径
    var str = new RegExp('http');
    var newUrl;
    //通过三元运算符进行判断该图片是否含有http域名，没有就拼接上去
    str.test(url) ? newUrl = url : newUrl = imgUrl + url;
    return newUrl
  }
  // 获取相应值列表
  function getListvalue(valLsit, type){
    let list = []
      for(var i = 0, len = valLsit.length; i < len; i++) {
        if (valLsit[i].type == type) {
        list.push(valLsit[i])
        }
      }
      return list
  }
  function getSpliceAddress(name){
    var reg = getRegExp("/\//g");
    return name.replace("中国/", "").replace(reg, "-")
  }
  // 小程序打开页面上限处理
  function navigateTo(object){
    if (getCurrentPages().length > 9) {
        wx.redirectTo(object)
        // this.reLaunch(object)
    } else {
        wx.navigateTo(object)
    }
}
//生成四位随机字符
function randomS4() {
  return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
//用于生成uuid
function guid() {
  return (randomS4()+randomS4()+"-"+randomS4()+"-"+randomS4()+"-"+randomS4()+"-"+randomS4()+randomS4()+randomS4());
}
module.exports = {
  formatTime: formatTime,
  newFormatNumber: newFormatNumber,
  timedifference: timedifference,
  requestForm:requestForm,   //暴露form表单请求
  requestJson:requestJson,   //暴露json请求
  qqMapTransBMap,
  bMapTransQQMap,
  getImgUrl,
  getListvalue: getListvalue,
  navigateTo: navigateTo,
  guid:guid
}
